<?php
$inputfile = "hscodes.csv";
$outputfile = "hscodes.sql";

$currentHS2 = "";
$currentSection = array();

function processRow($counter, $rowdata, $out) {
    global $currentHS2;
    global $currentSection;

    if (stristr($rowdata[0], "SECTION") !== false) {
        $tmp = explode(" ", $rowdata[0]);
        $currentSection = array(
            num => $tmp[1],
            eng => $rowdata[1],
            hun => $rowdata[6],
        );
    } else if (stristr($rowdata[0], "CHAPTER") !== false) {
        $tmp = explode(" ", $rowdata[0]);
        $currentHS2 = array(
            num => $tmp[1],
            eng => $rowdata[1],
            hun => $rowdata[6],
        );
        $row = array(
            "'" . $currentHS2['num'] . "'",
            "'" . $currentHS2['eng'] . "'",
            "'" . $currentHS2['hun'] . "'",
        );
        fputs($out, "INSERT INTO hs_chapter (chapter, name_en, name_hu) VALUES (" . implode(",", $row) . ");\r\n");
    } else {
        return;
    }
}

$f = fopen($inputfile, "r");
$c = 0;
$out = fopen($outputfile,  "w");
$counter = $startindex;
while (!feof($f)) {
    $c++;
    $row = rtrim(fgets($f));
    $row = str_replace("\"", "", $row);
    $row = str_replace("'", "''", $row);
    $rowdata = explode("*", $row);
    processRow($counter, $rowdata, $out);
    $counter++;
}
fclose($f);
fclose($out);

?>
